<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
<script src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/picture/pika.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/picture/pika.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-LqqDM3vffE">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">


  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2efd5eff.js","daovoice")
  daovoice('init', {
    app_id: "2efd5eff"
  });
  daovoice('update');
  </script>


<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notspr.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":true,"color":"#ff7600","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="简介  Celery 是一款非常简单、灵活、可靠的分布式系统，可用于处理大量消息，并且提供了一整套操作此系统的一系列工具。 Celery 是一款专注于实时处理的异步任务队列，可用于处理实时数据以及任务调度。  Celery架构Celery的架构由三部分组成，消息中间件（message broker），任务执行单元（worker）和任务执行结果存储（task result store）组成。">
<meta property="og:type" content="article">
<meta property="og:title" content="Python之Celery">
<meta property="og:url" content="https://notspr.com/2020/08/20/celery/index.html">
<meta property="og:site_name" content="Sapphire">
<meta property="og:description" content="简介  Celery 是一款非常简单、灵活、可靠的分布式系统，可用于处理大量消息，并且提供了一整套操作此系统的一系列工具。 Celery 是一款专注于实时处理的异步任务队列，可用于处理实时数据以及任务调度。  Celery架构Celery的架构由三部分组成，消息中间件（message broker），任务执行单元（worker）和任务执行结果存储（task result store）组成。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://notspr.com/2020/08/20/celery/celery-architecture.png">
<meta property="article:published_time" content="2020-08-19T17:11:44.000Z">
<meta property="article:modified_time" content="2020-12-02T17:41:09.568Z">
<meta property="article:author" content="Ryan Shu">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="Celery">
<meta property="article:tag" content="Django">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://notspr.com/2020/08/20/celery/celery-architecture.png">

<link rel="canonical" href="https://notspr.com/2020/08/20/celery/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Python之Celery | Sapphire</title>
  


  <script data-pjax>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2907d577c8c6c2f7fe3843736d24280d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <!--pjax：防止跳转页面音乐暂停-->
  <script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.js"></script>
<link rel="alternate" href="/atom.xml" title="Sapphire" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Sapphire</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">興趣使然的博客</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/aboutme/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">82</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">34</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">40</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/sususama5555" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://notspr.com/2020/08/20/celery/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/picture/avatar.jpg">
      <meta itemprop="name" content="Ryan Shu">
      <meta itemprop="description" content="全栈 | 硬件 | 篮球 | 游戏">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sapphire">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Python之Celery
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-20 01:11:44" itemprop="dateCreated datePublished" datetime="2020-08-20T01:11:44+08:00">2020-08-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/Celery/" itemprop="url" rel="index"><span itemprop="name">Celery</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.7k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3></blockquote>
<ul>
<li>Celery 是一款非常简单、灵活、可靠的分布式系统，可用于处理大量消息，并且提供了一整套操作此系统的一系列工具。</li>
<li>Celery 是一款专注于实时处理的异步任务队列，可用于处理实时数据以及任务调度。</li>
</ul>
<h3 id="Celery架构"><a href="#Celery架构" class="headerlink" title="Celery架构"></a>Celery架构</h3><p>Celery的架构由三部分组成，消息中间件（message broker），任务执行单元（worker）和任务执行结果存储（task result store）组成。</p>
<img data-src="/2020/08/20/celery/celery-architecture.png" class>

<a id="more"></a>

<h4 id="消息中间件"><a href="#消息中间件" class="headerlink" title="消息中间件"></a>消息中间件</h4><p>Celery本身不提供消息服务，但是可以方便的和第三方提供的消息中间件集成。包括，RabbitMQ Redis等等</p>
<h4 id="任务执行单元"><a href="#任务执行单元" class="headerlink" title="任务执行单元"></a>任务执行单元</h4><p>Worker是Celery提供的任务执行的单元，worker并发的运行在分布式的系统节点中。</p>
<h4 id="任务结果存储"><a href="#任务结果存储" class="headerlink" title="任务结果存储"></a>任务结果存储</h4><p>Task result store用来存储Worker执行的任务的结果，Celery支持以不同方式存储任务的结果，包括AMQP, redis等</p>
<h3 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h3><p>异步任务：将耗时操作任务提交给Celery去异步执行，比如发送短信/邮件、消息推送、音视频处理等等</p>
<p>定时任务：定时执行某件事情，比如每天数据统计</p>
<h3 id="Celery的安装配置"><a href="#Celery的安装配置" class="headerlink" title="Celery的安装配置"></a>Celery的安装配置</h3><p><code>pip install celery</code></p>
<p>中间人（Broker）消息中间件：RabbitMQ / Redis</p>
<h4 id="RabbitMQ"><a href="#RabbitMQ" class="headerlink" title="RabbitMQ"></a>RabbitMQ</h4><p>RabbitMQ 是默认的中间人（Broker），只需要配置连接的URL即可，不需要安装额外的的配置以及初始化配置信息</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">broker_url = <span class="string">'amqp://myuser:mypassword@localhost:5672/myvhost'</span></span><br></pre></td></tr></table></figure>

<p>有关 Celery 各种中间人（Broker）的配置列表，请查阅代理设置，并且按照说明设置用户名和密码。</p>
<p><code>RabbitMQ</code>的安装和使用这里不多赘述，有空新开一篇文章讲解</p>
<h4 id="Redis"><a href="#Redis" class="headerlink" title="Redis"></a>Redis</h4><p>Redis 的配置非常的简单，只需要配置 Redis 的 URL ：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">app.conf.broker_url &#x3D; &#39;redis:&#x2F;&#x2F;localhost:6379&#x2F;0&#39;</span><br></pre></td></tr></table></figure>

<p>URL 的格式为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">redis:&#x2F;&#x2F;:password@hostname:port&#x2F;db_number</span><br></pre></td></tr></table></figure>

<p>URL 的所有配置都可以自定义配置的，默认使用的是 localhost 的 6379 端口中 0 数据库。（ Redis 默认有 16 个数据库）</p>
<p>Celery 也可以连接 Redis 哨兵也是非常简单的：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">app.conf.broker_url = <span class="string">'sentinel://localhost:26379;sentinel://localhost:26380;sentinel://localhost:26381'</span></span><br><span class="line">app.conf.broker_transport_options = &#123;<span class="string">'master_name'</span>:<span class="string">'cluster1'</span>&#125;</span><br></pre></td></tr></table></figure>

<h4 id="RabbitMQ-Redis-比较"><a href="#RabbitMQ-Redis-比较" class="headerlink" title="RabbitMQ / Redis 比较"></a>RabbitMQ / Redis 比较</h4><ul>
<li><p><a href="https://www.rabbitmq.com/" target="_blank" rel="noopener">RabbitMQ</a> 的功能比较齐全、稳定、便于安装。在生产环境来说是首选的。</p>
</li>
<li><p><a href="https://redis.io/" target="_blank" rel="noopener">Redis</a> 功能比较全，但是如果突然停止运行或断电会造成数据丢失。</p>
</li>
</ul>
<p>个人比较喜欢Redis作为Broker，Redis安装和使用比较简单，之所以Redis能够用作消息队列，因为其中的列表数据类型，可以存储多个有序的字符串，既然是有序的，就满足消息队列的特点，使用<code>lpush</code>+<code>rpop</code>或者<code>rpush</code>+<code>lpop</code>实现消息队列。除此之外，redis支持阻塞操作，在弹出元素的时候使用阻塞命令来实现阻塞队列。</p>
<p>以上已经在Redis分类的文章中有写到，新版Redis的特性也能更好地支持消息队列，这一块的知识后续新开一个文章进行学习。</p>
<h3 id="Celery异步任务"><a href="#Celery异步任务" class="headerlink" title="Celery异步任务"></a>Celery异步任务</h3><h4 id="创建任务"><a href="#创建任务" class="headerlink" title="创建任务"></a>创建任务</h4><p>tasks.py：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> celery <span class="keyword">import</span> Celery</span><br><span class="line">app = Celery(<span class="string">'tasks'</span>, broker=<span class="string">'amqp://guest@localhost//'</span>)</span><br><span class="line"><span class="meta">@app.task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(x, y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x + y</span><br></pre></td></tr></table></figure>

<h4 id="调用任务"><a href="#调用任务" class="headerlink" title="调用任务"></a>调用任务</h4><p>需要调用我们创建的实例任务，可以通过 <code>delay()</code> 进行调用。</p>
<p><code>delay()</code> 是 <code>apply_async()</code> 的快捷方法，可以更好的控制任务的执行（详情：<a href><code>调用任务：Calling Tasks</code></a>）：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> tasks <span class="keyword">import</span> add</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>add.delay(<span class="number">4</span>, <span class="number">4</span>)</span><br></pre></td></tr></table></figure>

<h4 id="保存结果"><a href="#保存结果" class="headerlink" title="保存结果"></a>保存结果</h4><p>如果需要跟踪任务的状态，Celery 需要在某处存储任务的状态信息。Celery 内置了一些后端结果：<a href="https://www.sqlalchemy.org/" target="_blank" rel="noopener">SQLAlchemy/Django</a> ORM、<a href="http://memcached.org/" target="_blank" rel="noopener">Memcached</a>、<a href="https://redis.io/" target="_blank" rel="noopener">Redis</a>、 RPC (<a href="https://www.rabbitmq.com/" target="_blank" rel="noopener">RabbitMQ</a>/AMQP)以及自定义的后端结果存储中间件。</p>
<p>针对本次实例，我们使用 RPC 作为结果后端，将状态信息作为临时消息回传。后端通过 backend 参数指定给 Celery（或者通过配置模块中的 result_backend 选项设定）：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">app = Celery(<span class="string">'tasks'</span>, backend=<span class="string">'rpc://'</span>, broker=<span class="string">'pyamqp://'</span>)</span><br></pre></td></tr></table></figure>

<p>例如，可以使用Redis作为Celery结果后端，使用RabbitMQ作为中间人（Broker）可以使用以下配置（这种组合比较流行）：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">app = Celery(<span class="string">'tasks'</span>, backend=<span class="string">'redis://localhost'</span>, broker=<span class="string">'pyamqp://'</span>)</span><br></pre></td></tr></table></figure>

<p><code>ready()</code> 可以检测是否已经处理完毕：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>result = add.delay(<span class="number">4</span>, <span class="number">4</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>result.ready()</span><br><span class="line"><span class="literal">False</span></span><br></pre></td></tr></table></figure>

<p>整个任务执行过程为异步的，如果一直等待任务完成，会将异步调用转换为同步调用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>result.get(timeout=<span class="number">1</span>)</span><br><span class="line"><span class="number">8</span></span><br></pre></td></tr></table></figure>

<p>如果任务出现异常，<code>get()</code> 会再次引发异常，可以通过 propagate 参数进行覆盖：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>result.get(propagate=<span class="literal">False</span>)</span><br></pre></td></tr></table></figure>

<p>如果任务出现异常，可以通过以下命令进行回溯：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>result.traceback</span><br></pre></td></tr></table></figure>

<h3 id="Celery执行定时任务"><a href="#Celery执行定时任务" class="headerlink" title="Celery执行定时任务"></a>Celery执行定时任务</h3><p><code>celery beat</code> 是一个调度程序；它定期启动任务，然后由集群中的可用节点执行任务。</p>
<h4 id="设定时间让celery执行一个任务"><a href="#设定时间让celery执行一个任务" class="headerlink" title="设定时间让celery执行一个任务"></a>设定时间让celery执行一个任务</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> celery_app_task <span class="keyword">import</span> add</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"></span><br><span class="line">ctime = datetime.now()</span><br><span class="line"><span class="comment"># 默认用utc时间</span></span><br><span class="line">utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> timedelta</span><br><span class="line">time_delay = timedelta(seconds=<span class="number">10</span>)</span><br><span class="line">task_time = utc_ctime + time_delay</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用apply_async并设定时间</span></span><br><span class="line">result = add.apply_async(args=[<span class="number">4</span>, <span class="number">3</span>], eta=task_time)</span><br></pre></td></tr></table></figure>

<h4 id="类似于contab的定时任务"><a href="#类似于contab的定时任务" class="headerlink" title="类似于contab的定时任务"></a>类似于contab的定时任务</h4><p>多任务结构中celery.py配置如下</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> timedelta</span><br><span class="line"><span class="keyword">from</span> celery <span class="keyword">import</span> Celery</span><br><span class="line"><span class="keyword">from</span> celery.schedules <span class="keyword">import</span> crontab</span><br><span class="line"></span><br><span class="line">cel = Celery(<span class="string">'tasks'</span>, broker=<span class="string">'redis://127.0.0.1:6379/1'</span>, backend=<span class="string">'redis://127.0.0.1:6379/2'</span>, include=[</span><br><span class="line">    <span class="string">'celery_task.tasks1'</span>,</span><br><span class="line">    <span class="string">'celery_task.tasks2'</span>,</span><br><span class="line">])</span><br><span class="line">cel.conf.timezone = <span class="string">'Asia/Shanghai'</span></span><br><span class="line">cel.conf.enable_utc = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">cel.conf.beat_schedule = &#123;</span><br><span class="line">    <span class="comment"># 名字随意命名</span></span><br><span class="line">    <span class="string">'add-every-10-seconds'</span>: &#123;</span><br><span class="line">        <span class="comment"># 执行tasks1下的test_celery函数</span></span><br><span class="line">        <span class="string">'task'</span>: <span class="string">'celery_task.tasks1.test_celery'</span>,</span><br><span class="line">        <span class="comment"># 每隔2秒执行一次</span></span><br><span class="line">        <span class="comment"># 'schedule': 1.0,</span></span><br><span class="line">        <span class="comment"># 'schedule': crontab(minute="*/1"),</span></span><br><span class="line">        <span class="string">'schedule'</span>: timedelta(seconds=<span class="number">2</span>),</span><br><span class="line">        <span class="comment"># 传递参数</span></span><br><span class="line">        <span class="string">'args'</span>: (<span class="string">'test'</span>,)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment"># 'add-every-12-seconds': &#123;</span></span><br><span class="line">    <span class="comment">#     'task': 'celery_task.tasks1.test_celery',</span></span><br><span class="line">    <span class="comment">#     每年4月11号，8点42分执行</span></span><br><span class="line">    <span class="comment">#     'schedule': crontab(minute=42, hour=8, day_of_month=11, month_of_year=4),</span></span><br><span class="line">    <span class="comment">#     'schedule': crontab(minute=42, hour=8, day_of_month=11, month_of_year=4),</span></span><br><span class="line">    <span class="comment">#     'args': (16, 16)</span></span><br><span class="line">    <span class="comment"># &#125;,</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>启动一个beat：celery beat -A celery_task -l info</p>
<p>启动work执行：celery worker -A celery_task -l info -P  eventlet</p>
<h3 id="Django中使用Celery"><a href="#Django中使用Celery" class="headerlink" title="Django中使用Celery"></a>Django中使用Celery</h3><p>在Django项目中异步任务和周期任务是必不可少的：</p>
<h4 id="添加Celery配置项"><a href="#添加Celery配置项" class="headerlink" title="添加Celery配置项"></a>添加Celery配置项</h4><p>在项目目录下创建celeryconfig.py（也可以写在settings.py中）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> djcelery</span><br><span class="line">djcelery.setup_loader()</span><br><span class="line"><span class="comment"># CELERY 配置，申明任务的文件路径，即包含有 @task 装饰器的函数文件</span></span><br><span class="line">CELERY_IMPORTS=(</span><br><span class="line">    <span class="string">'app01.tasks'</span>,</span><br><span class="line">)</span><br><span class="line"><span class="comment"># 有些情况可以防止死锁</span></span><br><span class="line">CELERYD_FORCE_EXECV=<span class="literal">True</span></span><br><span class="line"><span class="comment"># 设置并发worker数量</span></span><br><span class="line">CELERYD_CONCURRENCY=<span class="number">4</span></span><br><span class="line"><span class="comment"># 允许重试</span></span><br><span class="line">CELERY_ACKS_LATE=<span class="literal">True</span></span><br><span class="line"><span class="comment"># 每个worker最多执行100个任务被销毁，可以防止内存泄漏</span></span><br><span class="line">CELERYD_MAX_TASKS_PER_CHILD=<span class="number">100</span></span><br><span class="line"><span class="comment"># 超时时间</span></span><br><span class="line">CELERYD_TASK_TIME_LIMIT=<span class="number">12</span>*<span class="number">30</span></span><br><span class="line"></span><br><span class="line">CELERYBEAT_SCHEDULER = <span class="string">"djcelery.schedulers.DatabaseScheduler"</span></span><br></pre></td></tr></table></figure>

<h4 id="在app目录下创建tasks-py"><a href="#在app目录下创建tasks-py" class="headerlink" title="在app目录下创建tasks.py"></a>在app目录下创建tasks.py</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> celery <span class="keyword">import</span> task</span><br><span class="line"><span class="meta">@task</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(a,b)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(<span class="string">'a.text'</span>, <span class="string">'a'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> f:</span><br><span class="line">        f.write(<span class="string">'a'</span>)</span><br><span class="line">    print(a+b)</span><br></pre></td></tr></table></figure>

<h4 id="视图函数views-py"><a href="#视图函数views-py" class="headerlink" title="视图函数views.py"></a>视图函数views.py</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render,HttpResponse</span><br><span class="line"><span class="keyword">from</span> app01.tasks <span class="keyword">import</span> add</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment"># result=add.delay(2,3)</span></span><br><span class="line">    ctime = datetime.now()</span><br><span class="line">    <span class="comment"># 默认用utc时间</span></span><br><span class="line">    utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())</span><br><span class="line">    <span class="keyword">from</span> datetime <span class="keyword">import</span> timedelta</span><br><span class="line">    time_delay = timedelta(seconds=<span class="number">5</span>)</span><br><span class="line">    task_time = utc_ctime + time_delay</span><br><span class="line">    result = add.apply_async(args=[<span class="number">4</span>, <span class="number">3</span>], eta=task_time)</span><br><span class="line">    print(result.id)</span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">'ok'</span>)</span><br></pre></td></tr></table></figure>

<h4 id="Django的settings-py"><a href="#Django的settings-py" class="headerlink" title="Django的settings.py"></a>Django的settings.py</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 注册app</span></span><br><span class="line">INSTALLED_APPS = [</span><br><span class="line">    <span class="string">'djcelery'</span>,</span><br><span class="line">    <span class="string">'app'</span></span><br><span class="line">]</span><br><span class="line"><span class="keyword">from</span> djagocele <span class="keyword">import</span> celeryconfig</span><br><span class="line">BROKER_BACKEND=<span class="string">'redis'</span></span><br><span class="line">BROKER_URL=<span class="string">'redis://127.0.0.1:6379/1'</span></span><br><span class="line">CELERY_RESULT_BACKEND=<span class="string">'redis://127.0.0.1:6379/2'</span></span><br></pre></td></tr></table></figure>

<h4 id="周期任务"><a href="#周期任务" class="headerlink" title="周期任务"></a>周期任务</h4><p>celery beat是用来开启定时任务调度的，一般用法为：启动celery beat，然后启动worker，让beat去调用worker里面的任务。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> celery.schedules <span class="keyword">import</span> crontab</span><br><span class="line"><span class="keyword">from</span> celery.task <span class="keyword">import</span> task, periodic_task</span><br><span class="line"></span><br><span class="line"><span class="comment"># crontab设置每天8点</span></span><br><span class="line"><span class="comment"># @periodic_task(run_every=(crontab(minute=0, hour=8)))</span></span><br><span class="line"><span class="comment"># crontab设置每分钟</span></span><br><span class="line"><span class="meta">@periodic_task(run_every=crontab(minute="*/1"))</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">distribute_task</span><span class="params">()</span>:</span></span><br><span class="line">    now = datetime.datetime.now()</span><br><span class="line">    <span class="comment"># 使用周期任务调动异步任务</span></span><br><span class="line">    get_alarm_list.apply_async(args=(now,))</span><br><span class="line">    </span><br><span class="line"><span class="meta">@task()</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_alarm_list</span><span class="params">(source_time)</span>:</span></span><br><span class="line">    print(source_time)</span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>写了这么多，从Celery简介、架构，到消息队列选型，再Python中如何使用Celery、Django项目怎么配置集成Celery，也算是Celery的超详细讲解了，用了这么久Celery，总算填了一个坑哈哈。</p>
<p>想要学习Celery更多的设计、调度、优化、路由、并发、信号、调试、测试、扩展等详细内容，可以参考 <a href="https://www.celerycn.io/" target="_blank" rel="noopener">https://www.celerycn.io/</a></p>
<hr>
<p>参考链接：</p>
<p><a href="https://github.com/celery/celery" target="_blank" rel="noopener">Celery 源码 - Github</a></p>
<p><a href="https://github.com/celery/django-celery" target="_blank" rel="noopener">django-celery - Github</a></p>
<p><a href="https://github.com/celery/django-celery-beat" target="_blank" rel="noopener">django-celery-beat 源码 - Github</a></p>
<p><a href="https://www.celerycn.io/" target="_blank" rel="noopener">《Celery 中文手册》</a>  </p>
<p><a href="https://www.jianshu.com/p/620052aadbff" target="_blank" rel="noopener">Celery - 简书</a></p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Ryan Shu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://notspr.com/2020/08/20/celery/" title="Python之Celery">https://notspr.com/2020/08/20/celery/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/picture/weixin.png">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
              <a href="/tags/Redis/" rel="tag"><i class="fa fa-tag"></i> Redis</a>
              <a href="/tags/Celery/" rel="tag"><i class="fa fa-tag"></i> Celery</a>
              <a href="/tags/Django/" rel="tag"><i class="fa fa-tag"></i> Django</a>
              <a href="/tags/RabbitMQ/" rel="tag"><i class="fa fa-tag"></i> RabbitMQ</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/08/16/redis-use-case/" rel="prev" title="Redis修炼之使用场景">
      <i class="fa fa-chevron-left"></i> Redis修炼之使用场景
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/08/20/weixin-app/" rel="next" title="企业(政务)微信浏览器的前端开发兼容问题">
      企业(政务)微信浏览器的前端开发兼容问题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Celery架构"><span class="nav-number">2.</span> <span class="nav-text">Celery架构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#消息中间件"><span class="nav-number">2.1.</span> <span class="nav-text">消息中间件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#任务执行单元"><span class="nav-number">2.2.</span> <span class="nav-text">任务执行单元</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#任务结果存储"><span class="nav-number">2.3.</span> <span class="nav-text">任务结果存储</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用场景"><span class="nav-number">3.</span> <span class="nav-text">使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Celery的安装配置"><span class="nav-number">4.</span> <span class="nav-text">Celery的安装配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#RabbitMQ"><span class="nav-number">4.1.</span> <span class="nav-text">RabbitMQ</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Redis"><span class="nav-number">4.2.</span> <span class="nav-text">Redis</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RabbitMQ-Redis-比较"><span class="nav-number">4.3.</span> <span class="nav-text">RabbitMQ &#x2F; Redis 比较</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Celery异步任务"><span class="nav-number">5.</span> <span class="nav-text">Celery异步任务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#创建任务"><span class="nav-number">5.1.</span> <span class="nav-text">创建任务</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#调用任务"><span class="nav-number">5.2.</span> <span class="nav-text">调用任务</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#保存结果"><span class="nav-number">5.3.</span> <span class="nav-text">保存结果</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Celery执行定时任务"><span class="nav-number">6.</span> <span class="nav-text">Celery执行定时任务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#设定时间让celery执行一个任务"><span class="nav-number">6.1.</span> <span class="nav-text">设定时间让celery执行一个任务</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#类似于contab的定时任务"><span class="nav-number">6.2.</span> <span class="nav-text">类似于contab的定时任务</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Django中使用Celery"><span class="nav-number">7.</span> <span class="nav-text">Django中使用Celery</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#添加Celery配置项"><span class="nav-number">7.1.</span> <span class="nav-text">添加Celery配置项</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在app目录下创建tasks-py"><span class="nav-number">7.2.</span> <span class="nav-text">在app目录下创建tasks.py</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#视图函数views-py"><span class="nav-number">7.3.</span> <span class="nav-text">视图函数views.py</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Django的settings-py"><span class="nav-number">7.4.</span> <span class="nav-text">Django的settings.py</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#周期任务"><span class="nav-number">7.5.</span> <span class="nav-text">周期任务</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">8.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Ryan Shu"
      src="/picture/avatar.jpg">
  <p class="site-author-name" itemprop="name">Ryan Shu</p>
  <div class="site-description" itemprop="description">全栈 | 硬件 | 篮球 | 游戏</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">82</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/sususama5555" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sususama5555" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:876324872@qq.com" title="E-Mail → mailto:876324872@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/5330189327" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;5330189327" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://steamcommunity.com/profiles/76561198294148424/" title="steam → https:&#x2F;&#x2F;steamcommunity.com&#x2F;profiles&#x2F;76561198294148424&#x2F;" rel="noopener" target="_blank"><i class="fab fa-steam fa-fw"></i>steam</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>RSS</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://ddoudou.xyz/" title="http:&#x2F;&#x2F;ddoudou.xyz" rel="noopener" target="_blank">豆豆的博客</a>
        </li>
    </ul>
  </div>

      </div>

      <!-- 音乐播放器 -->
      
           <div>
              <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="210" height="110" src="//music.163.com/outchain/player?type=2&id=4226232&auto=1&height=66"></iframe>
           </div>
      

      <!-- 滚动条 -->
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">粤ICP备20063016号-2 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ryan Shu</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">180k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:44</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

    </div>
</body>
</html>
